package com.wk.springboot.config;

import com.wk.springboot.listener.JobCompletionNotificationListener;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableBatchProcessing
public class BatchConfiguration {

  @Autowired
  public JobBuilderFactory jobBuilderFactory;

  /**
   * RunIdIncrementer：job需要一个增量，用来维持数据的一个运行状态 flow：一系列的step
   * 这里stepN作为参数传进来，表示可以直接识别spring 容器中的bean
   * listener：当用JobBuilderFactory建造job时，监听自动有效
   */
//  @Bean
  public Job importUserJob(JobCompletionNotificationListener listener,
      Step step1,
      Step step2,
      Step step3,
      Step taskletStep,
      Step taskletAdapter,
      Step fileDeletingTaskletStep) {
    return jobBuilderFactory.get("importUserJob")
        .incrementer(new RunIdIncrementer())
        .listener(listener)
//        .flow(step1)
//        .end()
//        .start(step1)
        .start(taskletStep)
        .next(taskletAdapter)
        .next(fileDeletingTaskletStep)
        .build();
  }

  /**
   * 这个是有选择的执行job
   * 当myStep失败，则会走taskletAdapter
   * 否则会走taskletStep
   */
//  @Bean
  public Job transitionsJob (
      Step myStep,
      Step taskletStep,
      Step taskletAdapter) {
    return jobBuilderFactory.get("transitionsJob")
        .start(myStep).on("FAILED").to(taskletAdapter)
        .from(myStep).on("*").to(taskletStep)
        .end()
        .build();
  }

  /**
   * job读数据
   */
//  @Bean
  public Job flatFilesJob (
      Step flatFileStep) {
    return jobBuilderFactory.get("transitionsJob")
        .start(flatFileStep)
        .build();
  }
}
